<template>
  <!-- 卡片视图区域 -->
  <el-card>
    <el-row :gutter="20">
      <el-col :span="8">
        <!-- 搜索与添加区域 -->
        <el-input placeholder="请输入内容" >
          <template #append>
            <el-icon><search /></el-icon>
          </template>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addDept">添加部门</el-button>
      </el-col>
    </el-row>

    <el-table
      :data="allDept"
      style="width: 100%; margin-bottom: 20px;margin-top: 20px"
      row-key="id"
      border
      stripe
      default-expand-all
      :tree-props="{ children: 'deptLevelList', hasChildren: 'hasChildren' }"
      height="500px"
    >
      <el-table-column
        type="index"
        label="部门id"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="部门名称"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
      >
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="onEditClick(row)" />
          <el-button type="primary" size="small" :icon="Delete" @click="onDeleteClick(row)" />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="pagination"
      @current-change="handleContractCurrentChange"
      :current-page="page"
      :page-size="size"
      layout="total, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </el-card>

  <m-dialog v-model="dialogVisible" :title="title" @saveSubmit="submit">
    <el-form :model="form" label-width="120px">
      <el-form-item label="上级部门">
        <el-select v-model="form.parentId" placeholder="-">
          <el-option
            v-for="item in optionSelect"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="form.name" placeholder="请输入部门名称"/>
      </el-form-item>
      <el-form-item label="顺序">
        <el-input v-model="form.sort" placeholder="请输入部门顺序" type="num"/>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea"/>
      </el-form-item>
    </el-form>
  </m-dialog>

</template>

<script setup>
import { reactive, ref } from 'vue'
import { deptList, deptAdd, deptUpdate, deptDelete } from '@/api/dept'
import { Delete, Edit, Search } from '@element-plus/icons-vue'
import MDialog from '@/components/MDialog/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const dialogVisible = ref(false)
const title = ref('新增部门')
const isAdd = ref(true)

const total = ref(0)
const page = ref(1)
const size = ref(10)

const handleContractCurrentChange = currentPage => {
  page.value = currentPage
}

const submit = async () => {
  let result
  if (form.parentId === '') {
    form.parentId = 0
  }
  if (isAdd.value) {
    result = await deptAdd({
      name: form.name,
      parentId: form.parentId,
      seq: form.sort,
      remark: form.remark
    })
  } else {
    result = await deptUpdate({
      id: form.id,
      name: form.name,
      parentId: form.parentId,
      seq: form.sort,
      remark: form.remark
    })
  }
  if (result) {
    dialogVisible.value = false
    await getDeptList()
  }
}

const addDept = () => {
  for (const key in form) {
    form[key] = ''
  }
  isAdd.value = true
  if (!dialogVisible.value) {
    dialogVisible.value = true
  }
}

const onEditClick = (row) => {
  isAdd.value = false
  form.id = row.id
  form.parentId = row.parentId
  form.name = row.name
  form.sort = row.seq
  form.remark = row.remark
  if (!dialogVisible.value) {
    dialogVisible.value = true
  }
}

const onDeleteClick = (row) => {
  ElMessageBox.confirm('你确定要删除吗？')
    .then(() => {
      deptDelete(row.id).then((result) => {
        if (result) {
          ElMessage.info('删除成功')
          getDeptList()
        } else {
          ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
      // catch error
      ElMessage.error('删除失败')
    })
}

const allDept = ref([])
const getDeptList = async () => {
  allDept.value = await deptList()
  console.log(JSON.stringify(allDept.value))
  recursiveRenderDept(allDept.value)
  console.log(JSON.stringify(deptMap))

  recursiveRenderDeptSelect(allDept.value, 1)
  console.log(JSON.stringify(optionSelect.value))
}
getDeptList()

const deptMap = new Map()
const recursiveRenderDept = (deptList) => {
  if (deptList && deptList.length > 0) {
    deptList.forEach((dept) => {
      console.log('index : ' + dept.id)
      console.log('item : ' + JSON.stringify(dept))
      deptMap[dept.id] = dept
      if (dept.deptLevelList.length > 0) {
        recursiveRenderDept(dept.deptLevelList)
      }
    })
  }
}

const optionSelect = ref([
  {
    value: 0,
    label: '-'
  }
])
const recursiveRenderDeptSelect = (deptList, level) => {
  level = level | 0
  if (deptList && deptList.length > 0) {
    deptList.forEach((dept) => {
      console.log('index : ' + dept.id)
      console.log('item : ' + JSON.stringify(dept))
      deptMap[dept.id] = dept
      let blank = ''
      if (level > 1) {
        for (let j = 3; j <= level; j++) {
          blank += '..'
        }
        blank += '∟'
      }
      optionSelect.value.push({
        value: dept.id,
        label: blank + dept.name
      })
      if (dept.deptLevelList.length > 0) {
        recursiveRenderDeptSelect(dept.deptLevelList, level + 1)
      }
    })
  }
}

const form = reactive({
  id: '',
  parentId: '',
  name: '',
  sort: '',
  remark: ''
})

</script>

<style lang="scss" scoped>
@import '~@/style/mixin.scss';
@import '~@/style/variables.scss';

.app-wrapper {
  @include clearfix;
  position: relative;
  height: 100%;
  width: 100%;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0,0,0,0.15) !important;
}
</style>
